// ==UserScript==
// @name         Exhentai激活上一页按钮
// @namespace    http://tampermonkey.net/
// @description  当Exhentai首页的上一页按钮为灰时，将其替换为可点击链接
// @version      0.0.2-2024-11-16
// @match        https://exhentai.org/*
// @icon         https://exhentai.org/favicon.ico
// @grant        none
// @author       AgMonk
// @homepage     https://gitee.com/AgMonk/tampermonkey-script
// @downloadURL https://gitee.com/AgMonk/tampermonkey-script/raw/master/ehentai/ehentai-prev-page.user.js
// @updateURL https://gitee.com/AgMonk/tampermonkey-script/raw/master/ehentai/ehentai-prev-page.user.js

// ==/UserScript==

(function () {
    // 创建一个链接,设置属性
    const creatLink = (gid, elementId, text) => {
        let url = new URL(window.location.href);
        url.searchParams.delete("prev")
        url.searchParams.append("prev", gid)
        url.searchParams.delete("next")
        let a = document.createElement("a");
        a.href = url.toString()
        a.innerText = text
        a.id = elementId
        return a
    }
    // 替换一个按钮
    const replaceButton = (elementId) => {
        // 当前域名
        const origin = window.location.origin
        // 获取第一个链接的id
        const firstGalleryUrl = [...document.getElementsByTagName('a')].map(i => i.href).filter(i => i.startsWith(origin + "/g/"))[0]
        const targetElement = document.getElementById(elementId)
        if (!firstGalleryUrl || !targetElement || targetElement.tagName !== 'SPAN') return
        // 第一个画廊的gid
        const firstGid = firstGalleryUrl.split('/').map(i=>parseInt(i)).filter(i=>!isNaN(i))[0]
        targetElement.replaceWith(creatLink(firstGid, elementId, targetElement.innerText))
    }

    replaceButton("uprev")
    replaceButton("dprev")
})();
